import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class IO {

    private int inputValue;
    private boolean doingInput;

    private JTextField inputField;
    private JTextArea outputArea;

    private ActionListener inputListener;

    private void promptForInput(String str) {
	CPU cpu = LMC.getCPU();
	cpu.setStatus(str);
	cpu.appendStatus("Enter number between -500\n");
	cpu.appendStatus("and 499 in input field\n");
	cpu.appendStatus("then hit the \"Enter\" key\n");
	inputField.selectAll();
    }

    public IO() {
	super();
	doingInput = false;
	inputListener = new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		if (!doingInput) {
		    return;
		}
		String input = inputField.getText();
		try {
		    inputValue = Integer.parseInt(input);
		    if (inputValue >= -500 && inputValue < 500) {
			doingInput = false;
			inputField.setEditable(false);
			outputArea.append("> " + inputValue +"\n");
			outputArea.requestFocus();
			LMC.getCPU().putInput(inputValue);
			return;
		    }
		} catch(NumberFormatException f) {
		}
		promptForInput("Incorrect input.\n");
	    }
	};
    }

    public JComponent createVisual() {
	// FIXME - use helper method to wrap components in a JPanel.
	inputField = new JTextField(10);
	inputField.setEditable(false);
        inputField.setFont(LMC.font);
	inputField.addActionListener(inputListener);
	JPanel inputPanel = new JPanel(new FlowLayout());
	inputPanel.setBorder(BorderFactory.createTitledBorder("Input"));
	inputPanel.add(inputField);
	outputArea = new JTextArea(15, 10);
	outputArea.setEditable(false);
        outputArea.setFont(LMC.font);
	JScrollPane outputScrollPane = new JScrollPane(outputArea,
		JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
		JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
	outputScrollPane.setBorder(BorderFactory.createTitledBorder("Output"));
	JPanel ioPanel = new JPanel(new BorderLayout());
	ioPanel.add(inputPanel, BorderLayout.NORTH);
	ioPanel.add(outputScrollPane, BorderLayout.CENTER);
	return ioPanel;
    }

    public void updateDisplay() {
    }

    public void initiateInput() {
	inputField.setText("");
	inputField.setEditable(true);
	inputField.requestFocus();
	doingInput = true;
	promptForInput("");
    }

    public void output(int n) {
	outputArea.append("" + n + "\n");
    }

    public void clear() {
	inputField.setText("");
	outputArea.setText("");
    }

    public void initialize() {
	clear();
	inputField.setEditable(false);
	doingInput = false;
    }

}

